//
//  MusicPlayerViewController.m
//  Project_ZFR_MUSIC
//
//  Created by 张福润 on 16/2/26.
//  Copyright © 2016年 张福润. All rights reserved.
//

#import "MusicPlayerViewController.h"
#import "AudioPlayer.h"
#import "imageDownloadOperation.h"
#import "LyricTool.h"


@interface MusicPlayerViewController ()<imageDownloadOperationDelegate,AudioPlayerDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,assign,getter=isPlayingOrPause)BOOL playing;
@property (nonatomic,assign)CGFloat time;
@end

@implementation MusicPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self playMusic];
    [AudioPlayer shareAudioPlayer].delegate=self;
    self.sliderProgress.maximumValue=[self.musicModel.duration floatValue]/1000;
    self.sliderProgress.minimumValue=0;
    [self.sliderProgress addTarget:self action:@selector(seek:) forControlEvents:UIControlEventValueChanged];
    [self.sliderSound addTarget:self action:@selector(sound:) forControlEvents:(UIControlEventValueChanged)];
    
  
    
    // Do any additional setup after loading the vxiew from its nib.
}

#pragma mark - tableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell_id" ];
    if(!cell){
        cell=[[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell_id"];
    }
    LyricTool *model=[LyricTool shareLyricTool].modelArr[indexPath.row];
    cell.textLabel.text=model.lyric;
    cell.backgroundColor=[UIColor clearColor];
    if(self.singingIndex==indexPath){
        cell.textLabel.textColor=[UIColor redColor];
    }
    else{
        cell.textLabel.textColor=[UIColor cyanColor];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [LyricTool shareLyricTool].modelArr.count;
}



//声音
-(void)sound:(UISlider *)sender{
    [AudioPlayer shareAudioPlayer].volume=self.sliderSound.value;
}

-(void)timerAction{
    
    
    [UIView animateWithDuration:0 animations:^{
        self.imageViewMusic.transform=CGAffineTransformRotate(self.imageViewMusic.transform, .005f);
    }];
}
-(void)playFinish{

    [[AudioPlayer shareAudioPlayer]stop];
    [self.timer invalidate];
    self.playing=NO;
    self.timer=nil;
    [self buttonDownAction:nil];
    
}

-(void)seek:(UISlider *)sender{
    
    [[AudioPlayer shareAudioPlayer]seekToWithTime:sender.value];
}

-(void)playWithTime:(CGFloat)time{

    self.labelTimeBegin.text=[self timeFloat:time];
    self.labelTimeStop.text=[self timeFloat:[self.musicModel.duration floatValue]/1000-time];
    self.sliderProgress.value=time;
    
    
    NSInteger index=[[LyricTool shareLyricTool]indexForTime:time];
    if(index>=0){
        self.singingIndex=[NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
        [self.tableView reloadData];

    }
    
   
}

-(NSString *)timeFloat:(CGFloat)time{
    return [NSString stringWithFormat:@"%02d:%02d",(int)time/60,(int)time%60];
}


//播放
-(void)playMusic{
    self.playing=YES;
    
    if([AudioPlayer shareAudioPlayer].playing){
        [[AudioPlayer shareAudioPlayer]stop];
        [self.timer invalidate];
        self.timer=nil;
    }
    
    self.musicModel= self.arrayAll[self.number];
    [self imageDown:self.musicModel];
    self.title=self.musicModel.name;
    //歌词刷新
    LyricTool *lytool=[LyricTool shareLyricTool];
    [lytool lyricWithStr:self.musicModel.lyric];
    [self.tableView reloadData];
    
    [[AudioPlayer shareAudioPlayer]playerWithUrl:self.musicModel.mp3Url];
    self.timer=[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    self.playing=YES;
}
//上一首
- (IBAction)buttonUpAction:(id)sender {
    
    self.number-=1;
    if(self.number<0){
        self.number+=1;
    }
    else{
        self.imageViewMusic.transform=CGAffineTransformMakeRotation(0);
        self.singingIndex=0;
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
        [self playMusic];
    }
    
}
//暂停
- (IBAction)buttonPlayAction:(id)sender {
    [[AudioPlayer shareAudioPlayer]playerOrPause];
    self.playing=!self.playing;

    if(!self.playing){
        [self.timer invalidate];
        self.timer=nil;
    }
    else{
        self.timer=[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    
    
}
//下一首
- (IBAction)buttonDownAction:(id)sender {
    
    self.number+=1;
    if(self.number>self.arrayAll.count-1){
        self.number-=1;
    }
    else{
        self.imageViewMusic.transform=CGAffineTransformMakeRotation(0);
        self.singingIndex=0;
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
        [self playMusic];
    }
}

//下载图片
-(void)getImage:(UIImage *)image imageDownloadOperation:(imageDownloadOperation *)opetarion{
    self.imageViewMusic.image=image;
    [self.allImageDic setValue:image forKey:opetarion.picUrl];
}

-(void)getImageBlurPicImage:(UIImage *)blurPicImage imageDownloadOperation:(imageDownloadOperation *)opetarion{
    self.imageViewBlurPic.image=blurPicImage;

    UIImageView *imV=[[UIImageView alloc]initWithImage:blurPicImage];
    [self.tableView setBackgroundView:imV];
    [self.allImageBlurPicDic setValue:blurPicImage forKey:opetarion.blurPicUrl];
}


//图片下载
-(void)imageDown:(MusicModel *)model{
    if([self.allImageDic.allKeys containsObject:model.picUrl]&&[self.allImageBlurPicDic.allKeys containsObject:model.blurPicUrl]){
        self.imageViewMusic.image=self.allImageDic[model.picUrl];
        self.imageViewBlurPic.image=self.allImageBlurPicDic[model.blurPicUrl];
        UIImageView *imV=[[UIImageView alloc]initWithImage:self.allImageBlurPicDic[model.blurPicUrl]];
        [self.tableView setBackgroundView:imV];

    }
    else{
        imageDownloadOperation *imageDownload=[[imageDownloadOperation alloc]init];
        imageDownload.picUrl=model.picUrl;
        imageDownload.blurPicUrl=model.blurPicUrl;
        imageDownload.delegate=self;
        [self.queue addOperation:imageDownload];
    }
}


#pragma mark - 懒加载
-(NSMutableArray *)arrayAll{
    if(!_arrayAll){
        _arrayAll=[NSMutableArray array];
    }
    return _arrayAll;
}
-(NSOperationQueue *)queue{
    if(!_queue){
        _queue=[[NSOperationQueue alloc]init];
        _queue.maxConcurrentOperationCount=1;
    }
    return _queue;
}
-(NSMutableDictionary *)allImageDic {
    if(!_allImageDic){
        _allImageDic=[NSMutableDictionary dictionary];
    }
    return _allImageDic;
}
-(NSMutableDictionary *)allImageBlurPicDic{
    if(!_allImageBlurPicDic){
        _allImageBlurPicDic=[NSMutableDictionary dictionary];
    }
    return _allImageBlurPicDic;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
